//
//  SRSleepPart+Cate.m
//  SportRing
//
//  Created by Apple on 14/11/7.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRSleepPart+Cate.h"
#import "SRSleep+Cate.h"

@implementation SRSleepPart (Cate)

+ (SRSleepPart *)partForSleep:(SRSleep *)sleep
{
    __block SRSleepPart * part = nil;
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         part = [SRSleepPart MR_createEntity];
         part.sleep = sleep;
     }];
    return part;
}

- (void)configAttributesWithBlock:(void(^)(SRSleepPart * aSelf))block
{
    [MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:^(NSManagedObjectContext *localContext)
     {
         block(self);
     }];
}

@end

@implementation SRSleepPart (Find)

+ (NSArray *)findPartsForSleep:(SRSleep *)sleep
{
    return [sleep.sleepParts allObjects];
}

+ (SRSleepPart *)findPartForSleep:(SRSleep *)sleep filterByTimeStr:(NSString *)timeStr
{
    __block SRSleepPart * part = nil;
    [sleep.sleepParts enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        SRSleepPart * p = obj;
        if ([timeStr isEqualToString:p.timeStr]) {
            part = p;
            *stop = YES;
        }
    }];
    return part;
}

+ (SRSleepPart *)findPartCINEForSleep:(SRSleep *)sleep filterByTimeStr:(NSString *)timeStr
{
    SRSleepPart * part = [SRSleepPart findPartForSleep:sleep filterByTimeStr:timeStr];
    if (part == nil) {
        part = [SRSleepPart partForSleep:sleep];
        [part configAttributesWithBlock:^(SRSleepPart *aSelf) {
            aSelf.timeStr = timeStr;
        }];
    }
    return part;
}

@end